/*
 * Powered By XY
 * Since 2020
 */

package com.xy.biz.uc.manager.impl;

import com.xy.biz.uc.dao.ResourceDao;
import com.xy.biz.uc.domain.bo.ResourceBO;
import com.xy.biz.uc.domain.converter.ResourceConverter;
import com.xy.biz.uc.domain.query.ResourceQuery;
import com.xy.biz.uc.manager.ResourceManager;
import com.xy.lang.util.CollectionUtilsEx;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.List;

/**
 * 
 * 
 * @author zsp
 * @date 2020-8-19
 */
@Service
public class ResourceManagerImpl implements ResourceManager {

	@Autowired
	private ResourceDao resourceDao;
	
	@Override
	public int updateResource(ResourceBO resourceBO) {
		return resourceDao.updateResource(ResourceConverter.toPO(resourceBO));
	}
	
	@Override
	public ResourceBO getResource(Long resourceId) {
		return ResourceConverter.fromPO(resourceDao.getResource(resourceId));
	}

	@Override
	public List<ResourceBO> listResourceById(Collection<Long> collection) {
		return ResourceConverter.fromPO(resourceDao.listResourceById(collection));
	}
	
	@Override
	public List<ResourceBO> listResource(ResourceQuery query) {
		List<ResourceBO> resourceBOList = ResourceConverter.fromPO(resourceDao.listResource(query));
		if(query.getWithParentResource() != null && query.getWithParentResource().booleanValue()
				&& !CollectionUtils.isEmpty(resourceBOList)) {
			CollectionUtilsEx.foreachSetParent(resourceBOList,
					ResourceBO::getResourceId,
					ResourceBO::getParentResourceId,
					e -> ResourceConverter.fromPO(resourceDao.listResourceById(e)),
					(resourceBO, parentResourceBO) -> resourceBO.setParentResource(parentResourceBO));
		}
		return resourceBOList;
	}
	
	@Override
	public int countResource(ResourceQuery query) {
		return resourceDao.countResource(query);
	}
	
}
